import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus';
import viteCompression from 'vite-plugin-compression';
import { buildConfig } from './src/utils/build';
import prismjs from 'vite-plugin-prismjs';
import AutoImport from 'unplugin-auto-import/vite';
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

const pathResolve = (dir: string) => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		plugins: [
			vue(),
			vueSetupExtend(),
			prismjs({
				languages: ['json', 'html', 'css', 'javascript', 'typescript', 'java', 'python', 'go', 'c', 'php', 'sql', 'shell', 'xml', 'markdown', 'nginx', 'bash'],
			}),
			viteCompression(),
			JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.cdn() : null,
			AutoImport({
				// 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
				imports: ['vue'],
				resolvers: [
					// 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox...
					ElementPlusResolver(),
					// 自动导入图标组件
					IconsResolver({
						prefix: 'Icon',
					}),
				],
				eslintrc: {
					enabled: true,	// 是否开启 eslint 检测，默认为 true
				},
				// 配置文件生成位置，默认是根目录 /auto-imports.d.ts
				dts: './src/auto-imports.d.ts',
			}),
			Components({
				// 配置需要将哪些后缀类型的文件进行自动按需引入，'vue'为默认值
				extensions: ['vue'],
				// 解析的 UI 组件库，这里以 Element Plus 为例
				resolvers: [ElementPlusResolver(), IconsResolver({ enabledCollections: ['ep'] })],
				// 遍历子目录
				deep: true,
				// 配置文件生成位置，默认是根目录 /components.d.ts
				dts: './src/components.d.ts',
			}),
			Icons({
				autoInstall: true,
			}),
		],
		root: process.cwd(),
		resolve: { alias },
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		optimizeDeps: { exclude: ['vue-demi'], include: ['@kangc/v-md-editor/lib/theme/vuepress.js'] },
		server: {
			host: '0.0.0.0', // 服务启动的地址
			port: env.VITE_PORT as unknown as number, // 服务启动的端口
			open: JSON.parse(env.VITE_OPEN), // 服务启动时是否自动打开浏览器
			hmr: true, // 开启热更新
			proxy: {
				'/10086': {
					target: process.env.VITE_API_URL,
					ws: true,	// 是否启用websockets
					changeOrigin: true, // 开启代理服务器
					rewrite: (path) => path.replace(/^\/10086/, ''),
				},
			},
		},
		build: {
			outDir: 'dist',
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)?.groups!.moduleName ?? 'vender';
						}
					},
				},
				...(JSON.parse(env.VITE_OPEN_CDN) ? { external: buildConfig.external } : {}),
			},
		},
		css: { preprocessorOptions: { css: { charset: false } } },
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
